package io.renren.modules.sys.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import io.renren.common.utils.R;
import io.renren.common.config.AlipayConfig;
import io.renren.modules.order.controller.OrderController;
import io.renren.modules.study.entity.Course;
import io.renren.modules.order.entity.OrderEntity;
import io.renren.modules.pinKao.entity.PinKaoCourse;
import io.renren.modules.sys.entity.UserCourseBuyHistory;
import io.renren.modules.study.service.CourseService;
import io.renren.modules.pinKao.service.PinKaoService;
import io.renren.modules.sys.service.Test2Service;
import io.renren.modules.sys.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("api/test2")
public class TestController2 {
    @Autowired
    Test2Service service;

    @Autowired
    CourseService courseService;

    @Autowired
    PinKaoService pinKaoService;

    @Autowired
    TokenService tokenService;

    @Autowired
    OrderController orderController;

    @PostMapping("aaa")
    public R pay(@RequestBody Map map) {

        //第一步 要先查询数据库中这个课程的价格 传来课程的id
        //Course course = courseService.getCourseById((Integer) map.get("courseId"));

        String paytype = String.valueOf(map.get("payType"));
        if (paytype.equals("buycourse")){
            paytype = "1";
            Course course = courseService.getCourseById(Integer.parseInt(String.valueOf(map.get("courseId"))));
            String courseName = course.getTitle();
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.ALIPAY_URL, AlipayConfig.APP_ID,
                    AlipayConfig.PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,
                    AlipayConfig.SIGN_TYPE);

            AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();//创建API对应的request类
            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
            model.setBody("购买" + courseName);  //订单详情
            model.setSubject(courseName);  //订单标题
            String uuid = UUID.randomUUID().toString().replaceAll("-", "")+paytype;
            model.setOutTradeNo(uuid); // 订单号
            model.setTimeoutExpress("30m");  //支付时长
            model.setTotalAmount(map.get("totalAmount").toString());   //价格
            model.setProductCode("QUICK_MSECURITY_PAY");
            request.setBizModel(model);
            request.setNotifyUrl(AlipayConfig.CALLBACK_URL);
            AlipayTradeAppPayResponse response = null;//通过alipayClient调用API，获得对应的response类
            try {
                response = alipayClient.sdkExecute(request);
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
            return R.ok("支付请求成功", 100).put("data", response.getBody());

        }else {
            PinKaoCourse course = pinKaoService.getPinKaoCourseInfoByCourseId(Integer.valueOf(map.get("courseId").toString()) );
            Double price = Double.valueOf(course.getNowMoney());
            String courseName = course.getTitle();
             if (paytype.equals("launch")){
                paytype ="2";

            }else if (paytype.equals("join")){
                paytype ="3";
            }else if(paytype.equals("studyclass")){
                 paytype="4";
             }
            //第二步 对比支付的价格 只能相同才能购买
            Double payPrice = Double.valueOf(map.get("totalAmount").toString()) ;
            //判断
            if ((payPrice+"").equals(price+"")) {

                AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.ALIPAY_URL, AlipayConfig.APP_ID,
                        AlipayConfig.PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,
                        AlipayConfig.SIGN_TYPE);

                AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();//创建API对应的request类
                AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
                model.setBody("购买" + courseName);  //订单详情
                model.setSubject(courseName);  //订单标题
                String uuid = UUID.randomUUID().toString().replaceAll("-", "")+paytype;
                model.setOutTradeNo(uuid); // 订单号
                model.setTimeoutExpress("30m");  //支付时长
                model.setTotalAmount(map.get("totalAmount").toString());   //价格
                model.setProductCode("QUICK_MSECURITY_PAY");
                request.setBizModel(model);
                request.setNotifyUrl(AlipayConfig.CALLBACK_URL);
                AlipayTradeAppPayResponse response = null;//通过alipayClient调用API，获得对应的response类
                try {
                    response = alipayClient.sdkExecute(request);

                } catch (AlipayApiException e) {
                    e.printStackTrace();
                }
                // System.out.print(response.getBody());
                //String orderInfo = response.get
                //将数据存储到数据库中 订单状态为未关闭

                //生成一个未付款的订单
                UserCourseBuyHistory userCourseBuyHistory = new UserCourseBuyHistory();
                userCourseBuyHistory.setOrderNum(uuid);
                userCourseBuyHistory.setPrice(Double.valueOf(map.get("totalAmount").toString()));
                userCourseBuyHistory.setStatus("待付款");
                userCourseBuyHistory.setUserId(tokenService.getUserIdByToken(map.get("token")+""));

                courseService.addOrderInfo(userCourseBuyHistory);
                if("1".equals(paytype)){
                    //课程
                    //创建未付款的订单
                    OrderEntity orderEntity = new OrderEntity();
                    orderEntity.setOrderType("课程");
                    orderEntity.setPayment(map.get("totalAmount").toString());
                    orderEntity.setUserId(tokenService.getUserIdByToken(map.get("token").toString()));
                    orderEntity.setOrderId(uuid);
                    orderEntity.setShippingCode(UUID.randomUUID().toString().replace("-", ""));
                    orderController.insertOrder(orderEntity);
                }
                else if("4".equals(paytype)) {
                    //学习班
                    OrderEntity orderEntity = new OrderEntity();
                    orderEntity.setOrderType("学习班");
                    orderEntity.setPayment(map.get("totalAmount").toString());
                    orderEntity.setUserId(tokenService.getUserIdByToken(map.get("token").toString()));
                    orderEntity.setOrderId(uuid);
                    orderEntity.setShippingCode(UUID.randomUUID().toString().replace("-", ""));
                    orderController.insertOrder(orderEntity);
                }






                return R.ok("支付请求成功", 100).put("data", response.getBody());
            }


        }


        return R.error(101,"支付价格不正确,请重新支付");
    }
}
